<template>
  <Layout>
      <Form :label-width="120" ref="formInline" :model="formInline">
          <Row class="query-form">
              <Col span="8" >
                  <FormItem label="题库名称：" prop="bsaeQstInfo">
                      <Input v-model="formInline.bsaeQstInfo" />
                  </FormItem>
              </Col>
              <Col span="8">
                  <FormItem label="所属单位：">
                      <cascaderDom ref="queryOrgCascader" @setOrgInfo="setOrgId1" @setOrgname="setOrgName1"
                                   :rootOrgId="companyId"
                                   :orgTree="true"></cascaderDom>
                  </FormItem>
              </Col>
              <Col span="8">
                  <Button @click="cancel" class="ivu-btn-reset">重置</Button>
                  <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
              </Col>
          </Row>
      </Form>
      <Row class="query-form">
          <Col span="24">
              <Button size="large" class="ivu-btn-add" icon="md-add" @click="addModel">新增</Button>
              <Button size="large" class="ivu-btn-add" icon="md-cloud-upload"  @click="uploadAcc">导入</Button>
              <Button size="large" class="ivu-btn-add" icon="md-download"  @click="download">下载导入模板</Button>
              <Button size="large" class="ivu-btn-add" icon="md-cloud-download" :loading="exportLoading" @click="exportExcel">导出题库</Button>
          </Col>
      </Row>
      <Table ref='table'  :loading="loading" border :columns="baseColumns"
             :data="baseData" no-data-text="没有查询到相关数据!"  :height="tableHeight" highlight-row stripe size="small">
          <template slot-scope="{ row, index }" slot="select">
              <Radio v-model="row.selectCheck" @on-change="handleRowChange(row)">{{ "" }}</Radio>
          </template>
      </Table>
      <Row style="margin-right:10px;">
          <Col span="24">
              <Page :total="pagedata.total" :current="pagedata.currentPage" :page-size="pagedata.pageSize"
                    @on-page-size-change="pageSizeChange" @on-change="pageChange" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />
          </Col>
      </Row>
      <Modal v-model="modal1" title="题库配置" width="700" :mask-closable="false">
              <Form :label-width="100" ref="formCustom" :model="form1data" :rules="ruleCustom">
                  <Row>
                      <i-col>
                          <FormItem label="题库名称：" prop="bsaeQstInfo">
                              <Input v-model="form1data.bsaeQstInfo" show-word-limit :maxlength="200" placeholder="请输入..."/>
                          </FormItem>
                      </i-col>
                  </Row>
                  <Row>
                      <i-col>
                          <FormItem label="题库类型：" prop="bsaeQstState">
                              <Input v-model="form1data.bsaeQstState" show-word-limit :maxlength="200" placeholder="请输入..."/>
                          </FormItem>
                      </i-col>
                  </Row>
                  <Row>
                      <i-col>
                          <FormItem label="所属公司：" prop="companyId">
                              <cascaderDom ref="childOrg"
                                           @setOrgInfo='setOrgId'
                                           @setOrgname='setOrgName'
                                           :setCurrentName="{label:form1data.companyName,value:form1data.companyId}"
                                           :orgTree="true" :rootOrgId="companyId"></cascaderDom>
                          </FormItem>
                      </i-col>
                  </Row>
              </Form>
              <div slot="footer">
                  <Button  class='ivu-btn-save' :loading="buttonLoading" @click="saveInfo">确定</Button>
                  <Button class='ivu-btn-cancel' @click="closeModal">取消</Button>
              </div>
          </Modal>


      <Modal :mask-closable="false" :transfer=false  v-model="uploadEdit" :width=700 :title="this.baseQstInfo+'导入'" @on-cancel="close">
          <Form  ref="map" :show-message="false" :model="map" label-position="top">
              <Row type="flex" justify="space-around" class="code-row-bg">
                  <Col span="23">
                      <FormItem  label="" prop="file">
                          <div>
                              <Upload ref="upload1"
                                      :before-upload="handleUpload "
                                      :format="['xlsx', 'xls']"
                                      accept=".xlsx, .xls"
                                      :max-size="10240"
                                      type="drag"
                                      :action="''">
                                  <div style="padding: 10px">
                                      <Icon type="ios-cloud-upload" size="45" style="color: #3399ff"></Icon>
                                      <p>点击将文件拖拽到这里上传</p>
                                      <span style="font-size:8px;color: #797a64">仅支持上传单个excel </span>
                                  </div>
                              </Upload>
                          </div>
                          <div v-if="fileTrue">
                              <a>{{ map.file.name }}</a>
                              <Button type="text" icon="md-trash" @click="map.file = {},fileTrue = false" style="margin-left: 5px;margin-bottom: 3px"/>
                          </div>
                      </FormItem>
                  </Col>
              </Row>
          </Form>
          <div slot="footer">
              <Button type="primary" class='ivu-btn-save' :disabled="uploadDissabled" @click="submitFile('map')">确定</Button>
              <Button type="primary" class='ivu-btn-cancel' @click="close">取消</Button>
          </div>
      </Modal>

      <Modal title="导入详情" v-model="logInfoModel" :transfer=false :mask-closable="false">
          <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                  <div v-html="logInfo"></div>
              </Col>
          </Row>
          <div slot="footer">
              <Button type="primary" class='ivu-btn-cancel' @click="logInfoModel=false,logInfo=null">关闭</Button>
          </div>
      </Modal>
  </Layout>
</template>

<script>
    import {Api} from '@/api'
    import qs from "qs";
    import {sessionStorage, cookie} from '@/common/cacheUtils.js';
    import cascaderDom from "../../../../components/cascader-dom.vue"
    import {formatDate} from '@/tools/index'

    export default {
        name: "questionBase",
        components: {cascaderDom},
        data(){
            return{
                isUpdate: false,
                loading: true,
                formInline:{
                    bsaeQstInfo: ''
                },
                tableHeight: '',
                pageSizeArray: [10, 20, 50],
                pagedata: {
                    total: 0,
                    pageSize: 10,
                    currentPage: 1
                },
                modal1: false,
                form1data: {},
                ruleCustom: {
                    bsaeQstInfo: [{required: true, message: ' ',trigger: 'blur' }],
                    bsaeQstState: [{required: true,message: ' ',trigger: 'blur' }],
                    companyId:[{ required: true, message: ' ',trigger: 'blur'}],
                },
                baseColumns: [
                    {slot: 'select', title: '选择', width: 60, align: 'center', fixed: 'left'},
                    {type: 'index', title: '编号', width: 80, align: 'center', fixed: 'left'},
                    {title: '所属公司',minWidth:200, align: 'center', key: 'companyName'},
                    {title: '题库名称', minWidth:180,align: 'center', key: 'bsaeQstInfo',tooltip:true},
                    {title: '题库类型', minWidth:180,align: 'center', key: 'bsaeQstState',tooltip:true},
                    {title: '题目数量', minWidth:80,align: 'center', key: 'questionNum'},
                    {title: '题库创建时间', minWidth:90,align: 'center', key: 'createTime',render:(h, params)=> {
                        if (!params.row['createTime']) return "";
                        return h('span', formatDate(new Date(params.row['createTime']), "yyyy-MM-dd"))}},
                    {
                        title: '操作',
                        align: 'center',
                        key: 'view',
                        fixed: 'right',
                        width: 200,
                        render: (h, params) => {
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: (params.row.createUserId == sessionStorage('userId').getObject('userId').userId ||  this.Common.userIdList.includes(sessionStorage('userId').getObject('userId').userId )||sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
                                            ||sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined)? '':'#d0d0d0' ,
                                        pointerEvents: (params.row.createUserId == sessionStorage('userId').getObject('userId').userId ||  this.Common.userIdList.includes(sessionStorage('userId').getObject('userId').userId )||sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
                                            ||sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined)? '' : 'none'
                                    },
                                    on: {
                                        click: () => {
                                            this.form1data = params.row;
                                            this.isUpdate = true;
                                            this.modal1 = true;
                                        }
                                    }
                                }, '修改'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: (params.row.createUserId == sessionStorage('userId').getObject('userId').userId ||  this.Common.userIdList.includes(sessionStorage('userId').getObject('userId').userId )||sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
                                            ||sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined)? 'red':'#d0d0d0' ,
                                        pointerEvents: (params.row.createUserId == sessionStorage('userId').getObject('userId').userId ||  this.Common.userIdList.includes(sessionStorage('userId').getObject('userId').userId )||sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
                                            ||sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined) ? '' : 'none'
                                    },
                                    on: {
                                        click: () => {
                                            this.deleteRow(params.row);
                                        }
                                    }
                                }, '删除'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        marginRight: '10px',
                                        fontSize: '14px',
                                    },
                                    on: {
                                        click: () => {
                                            this.$router.push({path:'/questionList',query: {'bsaeQstId': params.row.bsaeQstId,type:(params.row.createUserId == sessionStorage('userId').getObject('userId').userId ||  this.Common.userIdList.includes(sessionStorage('userId').getObject('userId').userId )||sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined)?true:false}});
                                        }
                                    }
                                }, '题库详细')

                            ]);
                        }
                    }
                ],
                buttonLoading:false,
                baseData: [],
                companyId:'',

                selectId: '',
                selectChildId: this.selectId,
                uploadEdit: false,
                map:{},
                fileTrue:false,
                uploadDissabled:false,
                logInfoModel:false,
                logInfo:null,
                baseQstInfo: '',
                exportLoading: false,
            }
        },
        mounted(){
            this.companyId=sessionStorage('userId').getObject('userId').companyId
            this.tableHeight = window.innerHeight*0.85 - this.$refs.table.$el.offsetTop-40;
            this.query();
        },
        watch: {
            "modal1": function (qw, er) {
                if (qw && this.modal1) {
                    setTimeout(() => {
                        this.$refs.childOrg.setCurrentOrg();
                    }, 100)
                } else {
                    this.$refs.childOrg.resetCurrentOrg();
                    this.query()
                }
            },
        },
        methods:{
            query(){
                this.loading = true;
                let data = {
                    page: this.pagedata.currentPage,
                    rows: this.pagedata.pageSize,
                };
                if (this.formInline.companyId != null&&this.formInline.companyId != undefined&&this.formInline.companyId != '') {
                    this.formInline.orgId=this.formInline.companyId
                }else {
                    this.formInline.orgId = sessionStorage('userId').getObject('userId').companyId
                }
                data = Object.assign(data,JSON.parse(JSON.stringify(this.formInline)));
                this.$http.get(Api.questionBase,{
                    params:data,
                    paramsSerializer: params => {
                        return qs.stringify(params, { indices: false })
                    }
                }).then((res) => {
                    this.baseData = res.data.data.data;
                    this.selectId = null
                    this.baseData.forEach(m=>m.selectCheck=false)
                    this.pagedata.total = res.data.data.totalSize;
                    this.loading = false;
                }).catch( e => {
                    this.$Message.error('请求失败');
                });
            },

            handleRowChange(data) {
                this.baseQstInfo = data.bsaeQstInfo
                this.selectId = data.bsaeQstId
                this.baseData.splice()
                this.baseData.forEach(m=>{
                    m.selectCheck=false
                    if (data.bsaeQstId === m.bsaeQstId) {
                        m.selectCheck=true
                    }
                })
            },
            handleUpload (file) {
                this.map.file = file;
                this.fileTrue = true
                return false;
            },
            submitFile(map){
                if (this.fileTrue == false) {
                    return this.$Message.error("附件不能为空");
                }
                this.$refs[map].validate((valid) => {
                    if (valid) {
                        this.uploadDissabled = true
                        let formData = new FormData();
                        formData.append("file", this.map.file);
                        formData.append("bsaeQstId", this.map.bsaeQstId);
                        this.$http.post(Api.uploadQuestion, formData).then((res) => {
                            this.uploadDissabled = false
                            if (res.data.status == "200") {
                                this.logInfoModel = true
                                this.logInfo = res.data.data
                                this.query()
                            } else {
                                this.$Message.error(res.data.msg);
                            }
                            this.map={}
                            this.fileTrue = false
                            this.uploadEdit=false
                        }).catch(e => {
                            console.log(e);
                            this.uploadEdit=false
                            this.map={}
                            this.uploadDissabled = false
                            this.$Message.error("导入失败！请检查导入文档的格式是否正确");
                        })
                    } else {
                        this.$Message.error('请填报完整!');
                    }
                })

            },
            uploadAcc() {
                if (this.selectId == null || this.selectId === ''|| this.selectId === undefined) {
                    this.$Message.error('请先选择题库')
                } else {
                    this.map.bsaeQstId = this.selectId
                    this.selectChildId = this.selectId
                    this.uploadEdit = true
                }
            },
            download() {
                window.open('在线答题题库导入模板.xlsx','_blank')
            },
            close() {
                this.fileTrue = false
                this.map ={}
                this.uploadEdit = false
                this.query()
            },

            exportExcel() {
                if (this.selectId == null || this.selectId === '') {
                    this.$Message.error('请先选择题库')
                    return
                }
                this.exportLoading = true
                this.$http.get(Api.exportQuestion+this.selectId, {
                    responseType: 'blob'      //告诉服务器我们需要的响应格式
                }).then((res) => {
                    const aLink = document.createElement("a");
                    let blob = new Blob([res.data], {
                        type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
                    });
                    aLink.href = URL.createObjectURL(blob)
                    aLink.download = this.baseQstInfo+".xlsx" //标题
                    aLink.click()
                    document.body.appendChild(aLink)
                    this.exportLoading = false
                })
            },




            pageSizeChange(pageSize){
                this.pagedata.pageSize = pageSize;
                this.query();
            },
            pageChange(pageNum){
                this.pagedata.currentPage = pageNum;
                this.query();
            },
            cancel(){
                this.pagedata.currentPage = 1
                this.formInline = {};
                this.query();
                this.$refs.queryOrgCascader.resetCurrentOrg();
            },
            addModel(){
                this.form1data = {};
                this.modal1 = true;
                this.isUpdate=false
            },
            saveInfo(){
                this.$refs['formCustom'].validate((valid) => {
                    if(valid){
                        this.buttonLoading = true
                        this.$http.post(Api.questionBase, this.form1data).then((res) => {
                            this.query();
                            this.$Message.success({
                                content: '成功',
                                duration: 4
                            });

                            this.modal1 = false;
                          this.buttonLoading = false
                        }).catch( e => {
                            this.$Message.error({
                                content: '请求失败',
                                duration: 4
                            });
                          this.buttonLoading = false
                        });
                    }else {
                        this.$Message.error('请填报完整!');
                    }
                })
            },
            deleteRow(row){
                this.$Modal.confirm({
                    title: '数据删除',
                    content: '<p>确定删除该题库</p>',
                    okText: '确认',
                    onOk: () => {
                        this.$http.delete(Api.questionBase+'/'+row.bsaeQstId, {params:{
                                bsaeQstId: row.bsaeQstId
                            }}).then((res) => {
                            this.$Message.success({content:'确认成功',duration: 4});
                            this.modal1 = false;
                            this.query();
                        })
                    },
                    cancelText: '取消'
                });
            },
            closeModal(){
                this.form1data = {};
                this.modal1 = false;
            },
            setOrgId(data) {
                if (data && data instanceof Array && data.length > 0) {
                    this.$set(this.form1data, 'companyId', data[data.length - 1])
                } else {
                    this.form1data.companyId = null;
                }
            },
            setOrgName(data) {
                this.form1data.companyName = data;
            },
            setOrgId1(data) {
                this.formInline.companyId = data[data.length - 1];
            },
            setOrgName1(data) {
                this.formInline.companyName = data;
            },

        }
    }
</script>

<style lang='css' scoped>
@import '../../../../index.css';
</style>
